package com.cenntro.auth.controllers;

import java.util.List;

import javax.annotation.Resource;

import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.collections.Predicate;
import org.apache.commons.lang3.ArrayUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.cenntro.auth.model.dbo.SysPermissionDO;
import com.cenntro.auth.model.dbo.SysRolePermissionRefDO;
import com.cenntro.auth.model.dbo.SysSooidDO;
import com.cenntro.auth.model.dbo.SysSooidRoleRefDO;
import com.cenntro.auth.model.vo.SysPermissionTreeVO;
import com.cenntro.auth.model.vo.SysPermissionVO;
import com.cenntro.auth.service.SysPermissionService;
import com.cenntro.auth.service.SysRolePermissionRefService;
import com.cenntro.auth.service.SysSooidRoleRefService;
import com.cenntro.auth.utils.BeanFill;
import com.cenntro.auth.utils.PermissionTreeUtil;
import com.cenntro.auth.utils.Valid;
import com.cenntro.common.base.BaseController;
import com.cenntro.common.model.vo.PageVO;
import com.cenntro.common.model.vo.TreeVO;
import com.cenntro.common.util.ConvertorUtils;
import com.cenntro.common.util.MessageUtil;
import com.cenntro.common.util.result.PageResult;
import com.cenntro.common.util.result.Result;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.google.common.base.Function;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.Lists;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiModelProperty;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;


@Api(value="权限管理", tags={"权限管理"})
@RestController
@RequestMapping("/permission")
@Slf4j
public class PermissionController extends BaseController{

	@Resource
	private SysPermissionService sysPermissionService;
	
	@Resource
    private SysRolePermissionRefService sysRolePermissionRefService;
	
	@Resource
    private SysSooidRoleRefService sysSooidRoleRefService;
	/**
	 * 
	 * @param 
	 * @return
	 */
	@CrossOrigin
	@ApiOperation(value = "查询权限列表", notes = "查询权限列表")
	@RequestMapping(value="/selectPage")
	@ApiModelProperty(value = "权限列表")
	public Result selectPage(SysPermissionVO perm, PageVO pageVO){
		Page<SysPermissionDO> page = PageHelper.startPage(pageVO.getPage(), pageVO.getLimit(), true);
		SysPermissionDO sysPermissionDO = ConvertorUtils.deepConvert(perm, SysPermissionDO.class);
		List<SysPermissionDO> permList = sysPermissionService.selectPage(sysPermissionDO);
		
		
		
		return PageResult.ok(permList, page.getTotal());
	}
	
	/**
	 * 1、权限名称不能重复
	 * @param SysPermissionVO
	 * @return
	 */
//	@ApiParam( hidden = true)
	@ApiOperation(value = "权限新增", notes = "新增权限")
	@RequestMapping(value="/add")
	public Result add(@Validated(value={Valid.insert.class}) SysPermissionVO perm){
		log.info(perm.toString());
		SysPermissionDO sysPermissionDO = new SysPermissionDO();
		sysPermissionDO.setName(perm.getName());
		int count = sysPermissionService.selectCount(sysPermissionDO);
		if (count == 0){
			sysPermissionDO = ConvertorUtils.deepConvert(perm, SysPermissionDO.class);
			BeanFill.fillByCreate(sysPermissionDO);
			sysPermissionService.insert(sysPermissionDO);

            String pNode = null;
            if (perm.getPid() != null && perm.getPid() > 0) {
                SysPermissionDO parentPermDO = sysPermissionService.selectById(perm.getPid());
                pNode = StringUtils.join(parentPermDO.getPNode() + "_", sysPermissionDO.getPermissionId());
            } else {
                pNode = "0_" + sysPermissionDO.getPermissionId();
            }
            sysPermissionDO.setPNode(pNode);
            sysPermissionService.update(sysPermissionDO);
			return Result.ok();
		}else {
			return Result.error(MessageUtil.PARAM_ILLEGAL, MessageUtil.getMsg("PERMISSION_NAME_EXISTS", perm.getName()));
		}
	}
	/**
	 * 1、权限名称不能重复
	 * 2、id不能是空
	 * @param SysPermissionVO
	 * @return
	 */
	@ApiOperation(value = "修改权限", notes = "根据id修改权限")
	@RequestMapping(value="/update")
	public Result update(@Validated(value={Valid.update.class}) SysPermissionVO perm){
		log.info(perm.toString());
		SysPermissionDO sysPermissionDO = null;
		if (StringUtils.isNotBlank(perm.getName())){
			sysPermissionDO = sysPermissionService.selectOne(ImmutableMap.of("name", perm.getName()));
			if (sysPermissionDO != null){
				if(!sysPermissionDO.getPermissionId().equals(perm.getPermissionId())){
					return Result.error(com.cenntro.common.util.MessageUtil.PARAM_ILLEGAL, MessageUtil.getMsg("PERMISSION_NAME_EXISTS", perm.getName()));  //权限已经存在
				}
			}
		}
		sysPermissionDO = ConvertorUtils.deepConvert(perm, SysPermissionDO.class);
		BeanFill.fillByUpdate(sysPermissionDO);
		String pNode = null;
		if(perm.getPid() != null && perm.getPid() > 0){
            SysPermissionDO parentPermDO = sysPermissionService.selectById(perm.getPid());
            pNode = StringUtils.join(parentPermDO.getPNode() + "_" , sysPermissionDO.getPermissionId());
        }else{
            pNode = "0_" + sysPermissionDO.getPermissionId();
        }
		sysPermissionDO.setPNode(pNode);
		
		sysPermissionService.update(sysPermissionDO);
		return Result.ok();
	}
	/**
	 * 
	 * @param sysAuthVO
	 * @return
	 */
	@CrossOrigin
	@ApiOperation(value = "查询权限详情", notes = "查询权限详情")
	@RequestMapping(value="/selectById")
	@ApiModelProperty(value = "权限详细内容")
	public Result selectById( Integer permissionId){
		SysPermissionDO sysPermissionDO = sysPermissionService.selectById(permissionId);
		return Result.ok(sysPermissionDO);
	}
	
	/**
	 * 
	 */
	@ApiOperation(value = "推送权限列表", notes = "推送权限列表")
	@RequestMapping(value="/testRefreshPermission")
	@ApiModelProperty(value = "推送权限列表")
	public void refreshPermission(Integer userId){
		sysPermissionService.refreshPermission(userId);
	}
	
    /**
     * 
     * @param sysAuthVO
     * @return
     */
    @CrossOrigin
    @ApiOperation(value = "删除角色", notes = "删除角色")
    @RequestMapping(value="/delete")
    @ApiModelProperty(value = "删除角色")
    public Result delete(Integer permissionId){
        SysRolePermissionRefDO rpRef = new SysRolePermissionRefDO();
        rpRef.setRoleId(permissionId);
        int count = sysRolePermissionRefService.selectCount(rpRef);
        if(count > 0){
            return Result.error("有用户关联该角色，请先删除用户");
        }
        SysPermissionDO permissionDO = new SysPermissionDO();
        permissionDO.setPermissionId(permissionId);
        permissionDO.setStatus(-1);
        sysPermissionService.update(permissionDO);
        return Result.ok();
    }
    
    /**
     * 查询权限，tree的形式展示
     * @return
     */
    @ApiOperation(value = "tree的形式展示", notes = "tree的形式展示")
    @RequestMapping(value="/selectPermission4Tree")
    @ApiModelProperty(value = "查询权限，tree的形式展示")
    public Result selectPermission4Tree(){
        Subject subject = SecurityUtils.getSubject(); 
        SysSooidDO user = (SysSooidDO)subject.getPrincipal();
        SysSooidRoleRefDO roleRef = new SysSooidRoleRefDO();
        roleRef.setSooid(user.getId());
        List<SysSooidRoleRefDO> roleRefList = sysSooidRoleRefService.selectPage(roleRef);
        
        List<Integer> roles = Lists.transform(roleRefList, new Function<SysSooidRoleRefDO, Integer>() {
            @Override
            public Integer apply(SysSooidRoleRefDO input) {
                return input.getRoleId();
            }
        });
        
        List<SysPermissionDO> perms = sysPermissionService.selectPermByRoleIds(roles);
        CollectionUtils.filter(perms, new Predicate() {
            @Override
            public boolean evaluate(Object object) {
                SysPermissionDO  perm = (SysPermissionDO)object;
                if(perm.getType() == 0){
                    return false;
                }
                return true;
            }
        });
       
       Object tree = new PermissionTreeUtil<SysPermissionDO>() {
            @Override
            public boolean isRootId(SysPermissionDO e, TreeVO pNode) {
                if (e.getPNode().replace(e.getPermissionId().toString(), "").equals("0_")) {
                    return true;
                }
                return false;
            }
            @Override
            public boolean isParentId(SysPermissionDO e, TreeVO pNode) {
                String[] ids = e.getPNode().split("_");
                int index = ArrayUtils.indexOf(ids, pNode.getId().toString());
                return index == (ids.length - 2);
            }
            @Override
            public String getRootId(SysPermissionDO e, TreeVO pNode) {
                if (e.getPNode().replace(e.getPermissionId().toString(), "").equals("0_")) {
                    return e.getPermissionId().toString();
                } else {
                    return pNode.getRootId();
                }
            }
            @Override
            public void setField(SysPermissionDO e, TreeVO treeVO) {
                SysPermissionTreeVO vo = (SysPermissionTreeVO)treeVO;
                vo.setId(e.getPermissionId());
                vo.setName(e.getName());
                vo.setUrl(e.getUrl());
                vo.setStatus(e.getStatus());
                vo.setType(e.getType());
            }
        }.toTree(null, perms);

        return Result.ok(tree);
    }

}